package com.cgl.controller;

import com.auth0.jwt.interfaces.Claim;
import com.cgl.pojo.Article;
import com.cgl.pojo.Result;
import com.cgl.service.ArticleService;
import com.cgl.until.JwtUntil;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
public class ArticleController {
    private final Logger logger= LoggerFactory.getLogger(ArticleController.class);
    @Autowired
    private ArticleService articleService;
    @PostMapping("api/article/add")
    public Result addArticle(@RequestBody Article article){
        logger.info("添加文章:{}",article);
        if (article.getTitle()==null||article.getTitle().equals("")){
            return Result.error("文章标题不能为空");
        } else if (article.getContent()==null||article.getContent().equals("")) {
            return Result.error("文章内容不能为空");
        } else if (article.getImagePath()==null||article.getImagePath().equals("")){
            return Result.error("请上传文章封面");
        }
        else{
            int result=articleService.addArticle(article);
            if (result==1){
                return Result.success();
            } else if (result ==2) {
                return Result.error("文件保存失败");
            } else {
                return Result.error("添加失败");
            }
        }
    }

    @PostMapping("api/article/addByDraft")
    public Result addArticleByDraft(@RequestBody Article article){
        logger.info("添加草稿:{}",article);
        if (article.getTitle()==null||article.getTitle().equals("")){
            return Result.error("文章标题不能为空");
        } else if (article.getContent()==null||article.getContent().equals("")) {
            return Result.error("文章内容不能为空");
        } else if (article.getImagePath()==null||article.getImagePath().equals("")){
           return Result.error("请上传文章封面");
        }
        else{
            int result=articleService.addArticleByDraft(article);
            if (result==1){
                return Result.success();
            }
            else {
                return Result.error("添加失败");
            }
        }
    }
    @GetMapping("article/get")
    public Result getArticleById(@Param("id") String id){
        logger.info("获取文章:{}",id);
        Article article=articleService.getArticleById(id);
        if (article!=null){
            return Result.success(article);
        }
        else {
            return Result.error("获取失败");
        }
    }
    @GetMapping("article/getList")
    public Result getArticleList(@Param("pageIndex") int pageIndex,@Param("pageSize") int pageSize){
        logger.info("获取文章列表:{},{}",pageIndex,pageSize);
        if (pageIndex<0||pageSize<0){
            return Result.error("参数错误");
        }
        int start=pageIndex*pageSize;
        return Result.success(articleService.getArticl(start,pageSize));
    }
    @GetMapping("api/article/draft/getList")
    public Result getDraftList(@Param("pageIndex") int pageIndex,@Param("pageSize") int pageSize){
        logger.info("获取草稿列表:{},{}",pageIndex,pageSize);
        if (pageIndex<0||pageSize<0){
            return Result.error("参数错误");
        }
        int start=pageIndex*pageSize;
        return Result.success(articleService.getDraft(start,pageSize));
    }
    @GetMapping("article/conunt")
    public Result getAllArticleCount(){
        logger.info("获取文章总数");
        return Result.success(articleService.getAllArticleCount());
    }
    @GetMapping("api/article/draft/conunt")
    public Result getDarftCount(){
        logger.info("获取草稿总数");
        return Result.success(articleService.getAllDraftCount());
    }

    @GetMapping("article/getLast")
    public Result getArticleByLast(@Param("pageIndex") int pageIndex,@Param("pageSize") int pageSize){
        logger.info("获取最新文章:{},{}",pageIndex,pageSize);
        if (pageIndex<0||pageSize<0){
            return Result.error("参数错误");
        }
        return Result.success(articleService.getArticleByLast(pageIndex,pageSize));
    }
    @GetMapping("article/addviewCount")
    public Result addviewCount(@Param("id") String id){
        logger.info("增加文章浏览量:{}",id);
        if (id==null||id.equals("")){
            return Result.error("参数错误");
        }
        Boolean result=articleService.addviewCount(id);
        if (result){
            return Result.success();
        }
        else {
            return Result.error("增加失败");
        }
    }
    @GetMapping("article/addLikeCount")
    public Result addLikeCount(HttpServletRequest request,@Param("id") String id){
        String token;
        try {
            token = request.getHeader("LY-Authorization").replace("\"", "");
        }catch (NullPointerException e){
            return Result.error("用户未登录");
        }
        logger.info("用户登录:{}", token);

        if (!JwtUntil.verifyToken(token)){
            return Result.error("timeover");
        }

        Map<String, Claim> data = JwtUntil.decodeToken(token);

        logger.info("解码的JWT声明: {}", data);

        String userId = data.get("userId").asString();

        logger.info("用户:{}增加文章点赞量:{}",userId,id);

        if (id==null||id.equals("")){
            return Result.error("参数错误");
        }
        Boolean result=articleService.addLikeCount(userId,id);
        if (result){
            return Result.success();
        }
        else {
            return Result.error("增加失败");
        }
    }

    @GetMapping("article/getInfo")
    public Result getInfo(){
        logger.info("获取网站信息");
        return Result.success(articleService.getInfo());
    }

    @GetMapping("article/getRank")
    public Result getArticleRank(){
        logger.info("获取文章排行榜");
        return Result.success(articleService.getArticleRank());
    }

    @GetMapping("article/getLastRank")
    public Result getArticleLastRank(){
        logger.info("获取文章最新排行榜");
        return Result.success(articleService.getArticleLastRank());
    }

    @GetMapping("article/getLikeRank")
    public Result getArticleLikeRank(){
        logger.info("获取文章点赞排行榜");
        return Result.success(articleService.getArticleLikeRank());
    }

    @GetMapping("api/article/getAll")
    public Result getAllArticle(@Param("pageIndex") int pageIndex,@Param("pageSize") int pageSize){
        logger.info("获取所有文章:{},{}",pageIndex,pageSize);
        if (pageIndex<0||pageSize<0){
            return Result.error("参数错误");
        }
        HashMap<String,Object> map=new HashMap<>();
        int count=articleService.getAllArticleCount()+articleService.getAllDraftCount();
        List<Article> list=articleService.getAllArticle(pageIndex,pageSize);
        map.put("count",count);
        map.put("list",list);
        return Result.success(map);
    }

    @GetMapping("api/article/delete")
    public Result deleteArticle(@Param("id") String id){
        logger.info("删除文章:{}",id);
        if (id==null||id.equals("")){
            return Result.error("参数错误");
        }
        if (articleService.getArticleById(id)==null){
            return Result.error("文章不存在");
        }
        int result=articleService.deleteArticle(id);
        if (result==1){
            return Result.success();
        }
        else {
            return Result.error("删除失败");
        }
    }

    @PostMapping("api/article/update")
    public Result updateArticle(@RequestBody Article article){
        logger.info("更新文章:{}",article);
        if (article==null){
            return Result.error("参数错误");
        }
        int result=articleService.updataArticle(article);
        if (result==1){
            return Result.success();
        }
        else {
            return Result.error("更新失败");
        }
    }

}

